package com.epfly.promo.activity.impl.discount;

import com.epfly.iface.promo.activity.enums.DiscountTypeEnum;
import com.epfly.promo.activity.dao.ActivityFoodCategoryMapper;
import com.epfly.promo.activity.entity.ActivityEntity;
import com.epfly.promo.activity.entity.ActivityFoodCategoryEntity;
import com.epfly.promo.activity.entity.ActivityRuleEntity;
import com.epfly.promo.activity.feign.DataRestaurantFeignService;
import com.epfly.promo.activity.impl.discount.content.FoodCategoryRebate;
import com.google.common.collect.Sets;
import com.ifood.model.goods.param.response.food.FoodInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 5.菜品分类折扣;
 * {@link DiscountTypeEnum#FOOD_CATEGORY_REBATE}
 */
@Service
public class FoodCategoryRebateDiscountFunction extends AbstractDiscountFunction {

    @Resource
    private ActivityFoodCategoryMapper activityFoodCategoryMapper;

    @Resource
    private DataRestaurantFeignService dataRestaurantFeignService;

    @Override
    public BigDecimal doApply(ActivityWrapper activityWrapper, ActivityRuleEntity ruleEntity) {

        BigDecimal totalRebate = BigDecimal.ZERO;

        ActivityEntity activityEntity = activityWrapper.getActivityEntity();

        // 查出此优惠活动设置的所有的可享受折扣的菜品分类
        List<ActivityFoodCategoryEntity> foodCategoryEntities = activityFoodCategoryMapper.findByActivityId(activityEntity.getId());
        Set<String> foodCategoryIdSet = foodCategoryEntities.stream().map(ActivityFoodCategoryEntity::getRelationId).collect(Collectors.toSet());

        // 查出所有菜品信息
        List<FoodInfo> foodList = dataRestaurantFeignService.findFoodByFoodIdList(Sets.newHashSet(activityWrapper.getFoodIdList()));

        // 筛选出可享受折扣的菜品
        List<FoodInfo> rebateFoodList = foodList.stream().filter(e -> foodCategoryIdSet.contains(e.getCategoryId())).collect(Collectors.toList());

        if (CollectionUtils.isNotEmpty(rebateFoodList)) {
            FoodCategoryRebate foodCategoryRebate = gson.fromJson(ruleEntity.getRuleContent(), FoodCategoryRebate.class);

            for (FoodInfo foodInfo : rebateFoodList) {
                BigDecimal rebatedPrice = foodInfo.getVipPrice().multiply(foodCategoryRebate.getFixedDiscountPercent()).setScale(2, BigDecimal.ROUND_HALF_UP);
                if (foodInfo.getVipPrice().compareTo(rebatedPrice) > 0) { // 市价高于折扣价
                    totalRebate = totalRebate.add(foodInfo.getVipPrice().subtract(rebatedPrice));
                }
            }
        }

        return totalRebate;
    }

    @Override
    public Byte getDiscountType() {
        return DiscountTypeEnum.FOOD_CATEGORY_REBATE.getKey();
    }
}
